/** modified version
* @file			arduino.c
* @author  		Supachai Vorapojpisut
* @version 		0.3
* @date    		November 11, 2013
* @brief   		Arduino compatibility module - add Serial psedo-object
*/

/* Includes ------------------------------------------------------------------*/
#include "arduino.h"

/* Private define ------------------------------------------------------------*/
#define SERIAL_BUFFER_SIZE 	256

/* Private typedef -----------------------------------------------------------*/
typedef struct {
	uint8_t buffer[SERIAL_BUFFER_SIZE];
	volatile unsigned int head;
	volatile unsigned int tail;
} ring_buffer;

/* Private macro -------------------------------------------------------------*/
#define digitalPinToPort(P) 	( DIGITAL_PIN_TO_PORT[P] )
#define digitalPinToBitMask(P) 	( DIGITAL_PIN_TO_BIT_MASK[P] )

/* Private function prototypes -----------------------------------------------*/
void begin_fcn(uint32_t);
uint16_t available_fcn(void);
void flush_fcn(void);
char read_fcn(void);
char peek_fcn(void);
void write_fcn(unsigned char);
void print_fcn(char*);
void println_fcn(char*);  

/* Private variables ---------------------------------------------------------*/
GPIO_TypeDef *DIGITAL_PIN_TO_PORT[14]= {GPIOA, GPIOA, GPIOB, GPIOB, GPIOA, GPIOB, GPIOB, GPIOA, GPIOA, GPIOA, GPIOA, GPIOB, GPIOB, GPIOB};
uint16_t DIGITAL_PIN_TO_BIT_MASK[14] = {GPIO_Pin_3, GPIO_Pin_2, GPIO_Pin_12, GPIO_Pin_11, GPIO_Pin_7, GPIO_Pin_9, GPIO_Pin_8, GPIO_Pin_6, GPIO_Pin_5, GPIO_Pin_4, GPIO_Pin_11, GPIO_Pin_5, GPIO_Pin_4, GPIO_Pin_3};

static uint32_t msTick = 0;

static ring_buffer _rx_buffer;
static ring_buffer _tx_buffer;
static int transmitting = 0;

/* Private functions ---------------------------------------------------------*/

// SysTick handler to implement timebase features.
void SysTick_Handler()
{
	msTick++;
}


// Implementation of Serial.begin()
void begin_fcn(uint32_t baudRate) {
	USART_InitTypeDef usart_init_struct;
	GPIO_InitTypeDef gpio_init_struct;
	NVIC_InitTypeDef nvic_init_struct;
	
	// Enable and configure USART2 components
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
	usart_init_struct.USART_BaudRate = baudRate;
	usart_init_struct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	usart_init_struct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	usart_init_struct.USART_Parity = USART_Parity_No;
	usart_init_struct.USART_StopBits = USART_StopBits_1;
	usart_init_struct.USART_WordLength = USART_WordLength_8b;
	USART_Init(USART2, &usart_init_struct);
	
	// Enable AF features for pins PA3 and PA2
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource2 , GPIO_AF_1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource3 , GPIO_AF_1);

	// Configure Rx pin (D0) with AF
	gpio_init_struct.GPIO_Mode = GPIO_Mode_AF;
	gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
	gpio_init_struct.GPIO_Pin = digitalPinToBitMask(0);
	GPIO_Init(digitalPinToPort(0), &gpio_init_struct);
	
	// Configure Tx pin (D1) with AF
	gpio_init_struct.GPIO_OType = GPIO_OType_PP;
	gpio_init_struct.GPIO_Speed = GPIO_Speed_Level_3;
	gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
	gpio_init_struct.GPIO_Pin = digitalPinToBitMask(1);
	GPIO_Init(digitalPinToPort(1), &gpio_init_struct);
	
	// Configure NVIC with USART2 as interrupt source
	nvic_init_struct.NVIC_IRQChannel = USART2_IRQn;
	nvic_init_struct.NVIC_IRQChannelCmd = ENABLE;
	nvic_init_struct.NVIC_IRQChannelPriority = 0;
	NVIC_Init(& nvic_init_struct);
	
	// Enable USART2 with RXNE condition
	USART_Cmd(USART2, ENABLE);
	USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
	USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
	
	_rx_buffer.head = 0;
	_rx_buffer.tail = 0;
	_tx_buffer.head = 0;
	_tx_buffer.tail = 0;
}


// Implementation of Serial.available()
uint16_t available_fcn(void){
	return (uint16_t)(SERIAL_BUFFER_SIZE + _rx_buffer.head - _rx_buffer.tail) % SERIAL_BUFFER_SIZE;
}


// Implementation of Serial.flush()
void flush_fcn(void){
	while (transmitting && !USART_GetFlagStatus(USART2, USART_FLAG_TC));
	transmitting = 0;
}


// Implementation of Serial.read()
char read_fcn(void){
	if (_rx_buffer.head == _rx_buffer.tail) {
		return -1;
	} else {
		unsigned char c = _rx_buffer.buffer[_rx_buffer.tail];
		_rx_buffer.tail = (_rx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
		return c;
	}
}






// Implementation of Serial.peek()
char peek_fcn(void){
	if (_rx_buffer.head == _rx_buffer.tail) {
		return -1;
	} else {
		return _rx_buffer.buffer[_rx_buffer.tail];
	}
}


// Implementation of Serial.write()
void write_fcn(uint8_t byte){
	int i = (_tx_buffer.head + 1) % SERIAL_BUFFER_SIZE;

	// Send immediately if Tx buffer is empty and not transmitting
	if ( (_tx_buffer.head == _tx_buffer.tail) && !transmitting ) {
		USART_SendData(USART2, byte);
		USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
		transmitting = 1;
		return;
	}
	
	// Wait for empty space in buffer
	while (i == _tx_buffer.tail);
	
	_tx_buffer.buffer[_tx_buffer.head] = byte;
	_tx_buffer.head = i;
	
	USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
	transmitting = 1;
	USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
}


// Implementation of Serial.print()
void print_fcn(char *string){
	while (*string != 0) {
		write_fcn(*string);
		string++;
	}		
}


// Implementation of Serial.println()
void println_fcn(char *string){
	print_fcn(string);
	write_fcn('\r');
	write_fcn('\n');
}


// Interrupt handler
void USART2_IRQHandler()
{
	if (USART_GetITStatus(USART2, USART_IT_TXE) == SET) {
		if (_tx_buffer.head != _tx_buffer.tail) {
			USART_SendData(USART2, _tx_buffer.buffer[_tx_buffer.tail]);
			_tx_buffer.tail = (_tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
		} else {
			USART_ClearITPendingBit(USART2, USART_IT_TXE);
			USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
			transmitting = 0;
		}
	} 
	if (USART_GetITStatus(USART2, USART_IT_RXNE) == SET) {
		_rx_buffer.buffer[_rx_buffer.head] = USART_ReceiveData(USART2);
		_rx_buffer.head = (_rx_buffer.head + 1) % SERIAL_BUFFER_SIZE;
	}
}


/* Global functions ----------------------------------------------------------*/
Serial_TypeDef Serial = {
	0,
	begin_fcn,
	available_fcn,
	flush_fcn,
	read_fcn,
	peek_fcn,
	write_fcn,
	print_fcn,
	println_fcn,
};


/**
* @brief	Initialization code to configure STM32F0 Discovery board for Arduino compatibility
* @param	None
* @retval	None
*/
void platform_config()
{
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB, ENABLE);
	SysTick_Config(SystemCoreClock/1000);
}


/**
* @brief	Configures the specified pin to behave either as an input or an output. 
* @param	pin		the number of the pin whose mode you wish to set
* @param	mode	INPUT or OUTPUT
* @retval	None
*/
void pinMode(uint8_t pin, int mode)
{
	GPIO_InitTypeDef gpio_init_struct;
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	
	if (mode == OUTPUT) {
		gpio_init_struct.GPIO_Mode = GPIO_Mode_OUT;
		gpio_init_struct.GPIO_OType = GPIO_OType_PP;
		gpio_init_struct.GPIO_Speed = GPIO_Speed_Level_3;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_NOPULL;
		gpio_init_struct.GPIO_Pin = gpio_pin;
	} else {
		gpio_init_struct.GPIO_Mode = GPIO_Mode_IN;
		gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
		gpio_init_struct.GPIO_Pin = gpio_pin;		
	}
	GPIO_Init(gpio_port, &gpio_init_struct);
}


/**
* @brief	Reads the value from a specified digital pin, either HIGH or LOW.
* @param	pin		the number of the digital pin you want to read
* @retval	HIGH or LOW
*/
int digitalRead(uint8_t pin)
{
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	
	if (GPIO_ReadInputDataBit(gpio_port, gpio_pin) == Bit_SET) {
		return HIGH;
	}
	return LOW;
}


/**
* @brief	Write a HIGH or a LOW value to a digital pin.
* @param	pin		the pin number
* @param	value	HIGH or LOW
* @retval	None
*/
void digitalWrite(uint8_t pin, int value)
{
	GPIO_TypeDef *gpio_port = digitalPinToPort(pin);
	uint16_t gpio_pin = digitalPinToBitMask(pin);
	
	if (value == HIGH) {
		GPIO_WriteBit(gpio_port, gpio_pin, Bit_SET); 
	} else {
		GPIO_WriteBit(gpio_port, gpio_pin, Bit_RESET);
}
}


/**
* @brief	Pauses the program for the amount of time (in miliseconds) specified as parameter. 
* @param	ms		the number of milliseconds to pause
* @retval	None
*/
void delay(uint32_t ms)
{
	uint32_t start = msTick;
	while ((msTick - start) < ms);
}


/**
* @brief	Returns the number of milliseconds since the board began running the current program. 
* @param	None
* @retval	Number of milliseconds since the program started
* @remark	This number will overflow (go back to zero), after approximately 50 days.
*/
uint32_t millis(void)
{
	return msTick;
}
